var router = require('express').Router();
var util = require('util');
var EventProxy = require("eventproxy")
var async = require("async");

var Consts = require('../consts');
var resultJson = require('../result-json');
var Utils = require('../utils');
var logger = require('../models/logger');
var Report = require('../models/Report');
var User = require('../models/User');

router.post('/', function(req, res) {
	res.send('respond with a resource');
});

//查询举报
router.post('/list', function(req, res) {
	var proxy = new EventProxy();
	proxy.all("results", "count", function(results, count) {
		res.send(resultJson(0, {
			results: results,
			count: count
		}))
	})
	var start = req.body.start || 0;
	var count = req.body.count || Consts.MAX;

	var item = {};
	var status = req.body.status;
	if (status) {
		item = {
			status: status
		}
	}
	Report.find(item).sort({
		create: -1,
	}).skip(start).limit(count).exec(function(err, reports) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		reports = JSON.parse(JSON.stringify(reports));
		var result = [];
		async.eachSeries(reports, function(item, cb) {
			User.findOne({
				_id: item.from
			}, {
				_id: 1,
				name: 1
			}).exec(function(err, user) {
				if (err)
					cb(err);
				if (!user)
					user = {};

				item.from_user = user;
				User.findOne({
					_id: item.to
				}).exec(function(err, user2) {
					if (err)
						cb(err);
					if (!user2)
						user2 = {};
					item.to_user = user2;
					result.push(item);
					cb();
				});
			});
		}, function(err) {
			if (err) {
				logger.error(err);
				return res.send(resultJson(2));
			}
			proxy.emit("results", result);
		});
	});
	Report.find(item).count(function(err, num) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		proxy.emit("count", num);
	});
});

//添加或修改举报
router.post('/upsert', function(req, res) {
	var report = req.body;
	    report = JSON.stringify(report);
    report = report.replace(/\</g, '&lt;').replace(/\>/g, '&gt;').replace(/</g, '&lt;').replace(/>/g, '&lg;');
    report = JSON.parse(report);
	if (!report.content || !report.to)
		return res.send(resultJson(3));

	if (report._id) { //update
		Report.update({
			_id: report._id
		}, {
			$set: report
		}).exec(function(err) {
			if (err) {
				logger.error(err);
				return res.send(resultJson(2));
			}
			res.send(resultJson(0));
		});
	} else { //add
		report.create = new Date();
		report.from = req.body._user._id; //不需要前台传递参数
		new Report(report).save(function(err, report) {
			if (err) {
				logger.error(err);
				return res.send(resultJson(2));
			}
			res.send(resultJson(0, report));
		});
	}

});

//删除举报
router.post('/remove', function(req, res) {
	Report.remove({
		_id: req.body._id
	}, function(err) {
		if (err) {
			logger.error(err);
			res.send(resultJson(2));
		} else
			res.send(resultJson(0));
	})
});
module.exports = router;